/**
 * 测试WebSocket指令1265（杂物查询）
 */

const WebSocket = require('ws');

// WebSocket连接配置
const WS_URL = 'ws://cd521.xin:8206/user-service/websocket?t=test_token_123';

// 测试数据
const testCases = [
    {
        name: '杂物类查询 (t=3)',
        request: { c: 1265, d: { t: 3, pageNum: 0 } },
        expectedItems: 6
    },
    {
        name: '矿物类查询 (t=2)',
        request: { c: 1265, d: { t: 2, pageNum: 0 } },
        expectedItems: 30
    },
    {
        name: '无效类型查询 (t=1)',
        request: { c: 1265, d: { t: 1, pageNum: 0 } },
        expectedError: true
    }
];

class WS1265Tester {
    constructor() {
        this.ws = null;
        this.testResults = [];
    }

    // 连接WebSocket
    async connect() {
        return new Promise((resolve, reject) => {
            console.log('🔌 正在连接WebSocket...');

            this.ws = new WebSocket(WS_URL);

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    this.handleMessage(message);
                } catch (error) {
                    console.error('❌ 解析消息失败:', error.message);
                }
            });
        });
    }

    // 处理接收到的消息
    handleMessage(message) {
        console.log('📨 收到消息:', JSON.stringify(message, null, 2));

        // 检查是否是1265指令的响应
        if (message.act_id === 1265) {
            this.processTestResult(message);
        }
    }

    // 处理测试结果
    processTestResult(response) {
        const currentTest = this.testResults[this.testResults.length - 1];
        if (!currentTest) return;

        currentTest.actualResponse = response;
        currentTest.completed = true;

        // 验证响应格式
        if (response.code === 0) {
            console.log(`✅ 测试通过: ${currentTest.name}`);
            console.log(`   返回物品数量: ${response.list ? response.list.length : 0}`);

            if (response.list && response.list.length > 0) {
                console.log(`   第一个物品: ID=${response.list[0].id}, 名称=${response.list[0].name}, 价格=${response.list[0].price}`);
            }
        } else {
            console.log(`❌ 测试失败: ${currentTest.name}`);
            console.log(`   错误信息: ${response.msg || '未知错误'}`);
        }

        // 继续下一个测试
        this.runNextTest();
    }

    // 发送测试请求
    sendTestRequest(testCase) {
        return new Promise((resolve) => {
            console.log(`\n🧪 开始测试: ${testCase.name}`);
            console.log(`📤 发送请求:`, JSON.stringify(testCase.request, null, 2));

            // 记录测试信息
            this.testResults.push({
                name: testCase.name,
                request: testCase.request,
                expectedItems: testCase.expectedItems,
                expectedError: testCase.expectedError,
                completed: false,
                actualResponse: null
            });

            // 发送请求
            this.ws.send(JSON.stringify(testCase.request));

            // 设置超时
            setTimeout(() => {
                const currentTest = this.testResults[this.testResults.length - 1];
                if (!currentTest.completed) {
                    console.log(`⏰ 测试超时: ${testCase.name}`);
                    currentTest.completed = true;
                    currentTest.timeout = true;
                    this.runNextTest();
                }
            }, 5000);
        });
    }

    // 运行下一个测试
    runNextTest() {
        const currentIndex = this.testResults.length - 1;
        const nextIndex = currentIndex + 1;

        if (nextIndex < testCases.length) {
            setTimeout(() => {
                this.sendTestRequest(testCases[nextIndex]);
            }, 1000);
        } else {
            // 所有测试完成
            this.showFinalResults();
        }
    }

    // 显示最终结果
    showFinalResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('=' * 60);

        let passedTests = 0;
        let totalTests = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const testCase = testCases[index];
            let status = '❌ 失败';

            if (result.timeout) {
                status = '⏰ 超时';
            } else if (result.actualResponse) {
                if (testCase.expectedError) {
                    // 期望错误的测试
                    if (result.actualResponse.code !== 0) {
                        status = '✅ 通过';
                        passedTests++;
                    }
                } else {
                    // 期望成功的测试
                    if (result.actualResponse.code === 0 &&
                        result.actualResponse.list &&
                        result.actualResponse.list.length === testCase.expectedItems) {
                        status = '✅ 通过';
                        passedTests++;
                    }
                }
            }

            console.log(`${index + 1}. ${result.name}: ${status}`);
            if (result.actualResponse) {
                console.log(`   响应: code=${result.actualResponse.code}, 物品数量=${result.actualResponse.list ? result.actualResponse.list.length : 0}`);
            }
        });

        console.log(`\n🎯 测试完成: ${passedTests}/${totalTests} 通过`);

        // 关闭连接
        this.close();
    }

    // 关闭连接
    close() {
        if (this.ws) {
            this.ws.close();
            console.log('🔌 WebSocket连接已关闭');
        }
    }

    // 运行所有测试
    async runAllTests() {
        try {
            await this.connect();

            // 开始第一个测试
            setTimeout(() => {
                this.sendTestRequest(testCases[0]);
            }, 1000);

        } catch (error) {
            console.error('💥 测试运行失败:', error.message);
        }
    }
}

// 运行测试
async function main() {
    console.log('🎯 WebSocket指令1265测试工具');
    console.log('   目标：测试杂物查询功能\n');

    const tester = new WS1265Tester();
    await tester.runAllTests();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = WS1265Tester;
